(function($) {
	$(':text[rel~=sponsor-username]').live("blur", function(e) {
		e.preventDefault();
		var field = $(this);
		var sponsor_container = field.parents('div.field.sponsor');
		var form_container = field.parents('form');
		var placement_container = form_container.find('div.field.placement');
		var sponsor_username = field.val(), placement_username = placement_container.find(':text[rel~=placement-username]').val();

		if(sponsor_username == ''){
			sponsor_container.find('input[rel~=sponsor-id]').val('');
	    	sponsor_container.find('input[rel~=sponsor-name]').val('');
			return false;
		}
		
		placement_container.find(':text[rel~=placement-username]').prop('disabled', true);
		placement_container.find('select[rel~=placement-position]').prop('disabled', true).trigger('liszt:updated');
		form_container.find('input[type="submit"], input[type="button"], button').prop('disabled', true);
		field.prop('disabled', true);
		$.getJSON($(this).data('url'), {'username': sponsor_username, 'placement': placement_username})
		.always(function() {
	    	placement_container.find(':text[rel~=placement-username]').prop('disabled', false);
	    	placement_container.find('select[rel~=placement-position]').prop('disabled', false).trigger('liszt:updated');
	    	form_container.find('input[type="submit"], input[type="button"], button').prop('disabled', false);
			field.prop('disabled', false);
  		})
		.done(function(data) {
		    if(data.result == 'success'){
		    	sponsor_container.find('input[rel~=sponsor-id]').val(data.id);
		    	sponsor_container.find('input[rel~=sponsor-name]').val(data.name);
		    	placement_container.find(':text[rel~=placement-username]').focus();
		    } else {
		    	alert(data.msg);
		    	sponsor_container.find('input[rel~=sponsor-id]').val('');
		    	sponsor_container.find('input[rel~=sponsor-name]').val('');
			    field.val('').focus();
		    }
		})
		.fail(function(jqxhr, textStatus, error) {
			alert(ss.i18n._t('SponsorField.ERROR_LOADING', 'Error occur while loading, please try again.'));
		    sponsor_container.find('input[rel~=sponsor-id]').val('');
		    sponsor_container.find('input[rel~=sponsor-name]').val('');
		    field.val('').focus();
		});
	});
})(jQuery);
